//
//  VCOfQAADetailedInformation.m
//  LCOnePsychology
//
//  Created by li cheng on 16/9/23.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "VCOfQAADetailedInformation.h"
#import "BaseTableView.h"
#import "MJMacro.h"
#import "TVCellOfQAADetailedInformation.h"
#import "MJMacro.h"
#import "Masonry.h"
#import "BaseLabel.h"
// models
#import "AnswersOfDataQAADetailedInformation.h"
#import "DataOfQAADetailedInformation.h"
#import "QuestionOfDataQAADetailedInformation.h"
#import "ReplyOfAnswersDataQAADetailedInformation.h"
#import "ReplyuserOfReplyAnswersDataQAADetailedInformation.h"
#import "RootClassOfQAADetailedInformation.h"
#import "StateOfDataQAADetailedInformation.h"
#import "TagsOfQuestionDataQAADetailedInformation.h"
#import "UserOfAnswersDataQAADetailedInformation.h"
#import "UserOfQuestionDataQAADetailedInformation.h"
#import "UserOfReplyAnswersDataQAADetailedInformation.h"
//
#import "ZWYNetTool.h"
//
#import "UIImageView+WebCache.h"
#import "VCOfLogining.h"
@interface VCOfQAADetailedInformation ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) BaseTableView *tableViewOfQAADetailedInformation;
@property (nonatomic, assign) CGFloat heightOfLabel;
@property (nonatomic, strong) RootClassOfQAADetailedInformation *rootClassOfQAADetailedInformation;
@property (nonatomic, assign) NSInteger heightOfReplySmallTableView;
@property (nonatomic, assign) NSInteger indexPathRow;
// 动态回复框
@property (nonatomic, strong) BaseView *viewOfBackground;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, assign) CGSize keyboardSize;
@property (nonatomic, assign) NSRange rang;
@property (nonatomic, assign) NSRange rangOfReplyuser;
//
@property (nonatomic, strong) UIButton *buttonOfReply;
@end

@implementation VCOfQAADetailedInformation

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 创建 tableView
    [self createTableView];
    // 数据解析
    [self handleData];
    // 创建回复的对话框
    [self createReply];
    _indexPathRow = -1;
    _heightOfReplySmallTableView = 0;
    [self registerForKeyboardNotifications];
}
#pragma mark - 数据解析
- (void)handleData{
    NSLog(@"_mArrayOfData:%@", _question_id);
  [ZWYNetTool GET:[NSString stringWithFormat:@"http://yiapi.xinli001.com/v2/yi/get-qaquestion.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0&question_id=%@", _question_id] andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
//      NSLog(@"%@", result);
      _rootClassOfQAADetailedInformation = [RootClassOfQAADetailedInformation modelDic:result];
//
      [self.tableViewOfQAADetailedInformation reloadData];
  } andFailureBlock:^(NSError *error) {
      
  }];
}
#pragma mark - 创建 tableView
- (void)createTableView{
    self.tableViewOfQAADetailedInformation = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableViewOfQAADetailedInformation];
    self.tableViewOfQAADetailedInformation.delegate = self;
    self.tableViewOfQAADetailedInformation.dataSource = self;
    [self.tableViewOfQAADetailedInformation registerClass:[TVCellOfQAADetailedInformation class] forCellReuseIdentifier:@"TVCellOfQAADetailedInformation"];
    
}
#pragma mark - tableView 代理方法 row 数量的确定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _rootClassOfQAADetailedInformation.data.answers.count;
}
#pragma mark - talbeView de 高度返回
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 计算出回复的 label 的矩形范围
    CGRect newRect = [_rootClassOfQAADetailedInformation.data.answers[indexPath.row].content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 63, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
    // 让开始的小的 tableView 的高度 为0
    _heightOfReplySmallTableView = 0;
    // 算出 label 总的高度
    for (ReplyOfAnswersDataQAADetailedInformation *replyOfAnswersDataQAADetailedInformation in _rootClassOfQAADetailedInformation.data.answers[indexPath.row].reply) {
//        NSString *string =
//        replyOfAnswersDataQAADetailedInformation.user
        NSMutableString *stringReplyUser = [NSMutableString string];
        if (!replyOfAnswersDataQAADetailedInformation.replyuser.nickname) {
            stringReplyUser = [NSMutableString stringWithFormat:@"%@:", replyOfAnswersDataQAADetailedInformation.user.nickname];
        } else {
            stringReplyUser = [NSMutableString stringWithFormat:@"%@回复%@:", replyOfAnswersDataQAADetailedInformation.user.nickname, replyOfAnswersDataQAADetailedInformation.replyuser.nickname];
        }
        NSString *allOfString = [NSString stringWithFormat:@"%@%@", stringReplyUser, replyOfAnswersDataQAADetailedInformation.content];
        CGRect newRect = [allOfString boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 63 - 20 - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
        _heightOfReplySmallTableView = _heightOfReplySmallTableView + newRect.size.height;
    }
    CGFloat heightOfReplyBackView = 0;
    // 返回回复 view 的高度 + 40 的 button
    heightOfReplyBackView = _heightOfReplySmallTableView + 40;
    return newRect.size.height + 150 +  heightOfReplyBackView;
}
#pragma mark - tableView 代理方法 cell 的赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    TVCellOfQAADetailedInformation *cell = [tableView dequeueReusableCellWithIdentifier:@"TVCellOfQAADetailedInformation" forIndexPath:indexPath];
    // 避免重用问题, 采取这个方法创建 cell
    TVCellOfQAADetailedInformation *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[TVCellOfQAADetailedInformation alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TVCellOfQAADetailedInformation"];
    }
    // cell 的空间赋值
    cell.answersOfDataQAADetailedInformation = _rootClassOfQAADetailedInformation.data.answers[indexPath.row];
    [cell.userAvatarImageView sd_setImageWithURL:[NSURL URLWithString:_rootClassOfQAADetailedInformation.data.answers[indexPath.row].user.avatar] placeholderImage:[UIImage imageNamed:@"0"]];
    cell.userAvatarImageView.layer.cornerRadius = 10;
    cell.userAvatarImageView.clipsToBounds = YES;
    cell.userNicknameLabel.text = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].user.nickname;
    // 回答内容 label
    cell.answersContentLabel.text = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].content;
    cell.answersVotenumLabel.backgroundColor = [UIColor redColor];
    cell.answersCreatedLabel.text = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].created;
    cell.answersReplynumLabel.text = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].replynum;
    cell.answersVotenumLabel.text = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].votenum;
    cell.clickCommentReplyButton.tag = indexPath.row + 10;
    cell.backgroundColor = [UIColor whiteColor];
    // 下面的回复的小的 tableView 的高度
    _heightOfReplySmallTableView = 0;
    // 创建一个数组用来装每个回复文章评论者的 cell 的高度
    NSMutableArray *mArrayOfheightReplySmallTableView = [NSMutableArray array];
    for (ReplyOfAnswersDataQAADetailedInformation *replyOfAnswersDataQAADetailedInformation in _rootClassOfQAADetailedInformation.data.answers[indexPath.row].reply) {
        CGRect newRect = [replyOfAnswersDataQAADetailedInformation.content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 63, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
        NSString *string = [NSString stringWithFormat:@"%f", newRect.size.height + 1];
        [mArrayOfheightReplySmallTableView addObject:string];
        _heightOfReplySmallTableView = _heightOfReplySmallTableView + newRect.size.height + 1;
    }
    // 我的回复的背景 View
    cell.replyBackgroundView.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    // 计算出对应的文章回复者的回复内容
    CGRect newRect = [_rootClassOfQAADetailedInformation.data.answers[indexPath.row].content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 63, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
    // 改变 回复背景的 frame
    cell.replyBackgroundView.frame = CGRectMake(43, newRect.size.height + 100, SCREEN_WIDTH - 43 - 20, _heightOfReplySmallTableView + 40);
    // 改变下面评论者的 tableView frame 的高度
    cell.replyBackgroundView.tableViewOfReplyBackgroundView.frame = CGRectMake(10, 40, SCREEN_WIDTH - 43 - 20 - 20, _heightOfReplySmallTableView);
    // 创建回复的 button
    UIButton *buttonOfReply = [UIButton buttonWithType:UIButtonTypeSystem];
    [cell.replyBackgroundView addSubview:buttonOfReply];
    buttonOfReply.frame = CGRectMake(10, 5, SCREEN_WIDTH - 43 - 20 - 20, 30);
    [buttonOfReply setTitle:@"  ⌨️ 点击下方的评论可直接回复对方" forState:UIControlStateNormal];
    _buttonOfReply.tag = [_rootClassOfQAADetailedInformation.data.answers[indexPath.row].user_id integerValue];
    [buttonOfReply addTarget:self action:@selector(reply:) forControlEvents:UIControlEventTouchUpInside];
    buttonOfReply.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    buttonOfReply.backgroundColor = [UIColor whiteColor];
    // 创建数组, 储存最下面回复的文本
    NSMutableArray *mArrayOfReplyLabelText = [NSMutableArray array];
    NSMutableArray *mArrayOfRange = [NSMutableArray array];
    NSMutableArray *mArrayOfRangReplyuser  = [NSMutableArray array];
    for (ReplyOfAnswersDataQAADetailedInformation *replyOfAnswersDataQAADetailedInformation in _rootClassOfQAADetailedInformation.data.answers[indexPath.row].reply) {
        NSMutableString *stringReplyUser = [NSMutableString string];
        // 做判断, 有么有跟谁回复者, 有确定中总的回复文字
        if (!replyOfAnswersDataQAADetailedInformation.replyuser.nickname) {
            stringReplyUser = [NSMutableString stringWithFormat:@"%@:", replyOfAnswersDataQAADetailedInformation.user.nickname];
        } else {
            stringReplyUser = [NSMutableString stringWithFormat:@"%@回复%@:", replyOfAnswersDataQAADetailedInformation.user.nickname, replyOfAnswersDataQAADetailedInformation.replyuser.nickname];
        }
        NSString *allOfString = [NSString stringWithFormat:@"%@%@", stringReplyUser, replyOfAnswersDataQAADetailedInformation.content];
        // 做判断, 有么有跟谁回复者, 有确定中关键字高亮的范围
        if (!replyOfAnswersDataQAADetailedInformation.replyuser.nickname) {
           _rang = [allOfString rangeOfString:replyOfAnswersDataQAADetailedInformation.user.nickname];
            _rangOfReplyuser = NSMakeRange(0, 0);
        } else {
            stringReplyUser = [NSMutableString stringWithFormat:@"%@回复%@:", replyOfAnswersDataQAADetailedInformation.user.nickname, replyOfAnswersDataQAADetailedInformation.replyuser.nickname];
            _rang = [allOfString rangeOfString:replyOfAnswersDataQAADetailedInformation.user.nickname];
            _rangOfReplyuser = [allOfString rangeOfString:replyOfAnswersDataQAADetailedInformation.replyuser.nickname];
        }
        [mArrayOfReplyLabelText addObject:allOfString];
        NSString *stringOfRange = [NSString stringWithFormat:@"%ld^(*￣(oo)￣)^%ld", _rang.location, _rang.length];
        NSLog(@"%@", stringOfRange);
        [mArrayOfRange addObject:stringOfRange];
        NSString *stringOfRangReplyuser = [NSString stringWithFormat:@"%ld^(*￣(oo)￣)^%ld", _rangOfReplyuser .location, _rangOfReplyuser.length];
        [mArrayOfRangReplyuser addObject:stringOfRangReplyuser];
    }
    // 给 cell 传属性 row 的数量
    cell.replyBackgroundView.numberOfRowsInSection = _rootClassOfQAADetailedInformation.data.answers[indexPath.row].reply.count;
    // row 的高度
    cell.replyBackgroundView.mArrayOfRowHeight = mArrayOfheightReplySmallTableView;
    // cell label 的 text
    // 给 replyBackgroundView 传递 label 的 text 的数组
    cell.replyBackgroundView.mArrayOfReplyLabel = mArrayOfReplyLabelText;
    // 给 replyBackgroundView 传递 label 的关键字高亮 rang 的数组
    cell.replyBackgroundView.mArrayOfRange = mArrayOfRange;
    // 给 replyBackgroundView 传递 label 的关键字高亮 rang 的数组
    cell.replyBackgroundView.mArrayOfRangReplyuser = mArrayOfRangReplyuser;
    return cell;
}
//#pragma mark - clickCommentReplyButton 方法实现
- (void)clickCommentReplyButton:(UIButton *)button{

}
#pragma 给键盘注册通知
- (void)registerForKeyboardNotifications
{
    // 给键盘隐藏添加方法选择器
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
    // 给键盘改变添加方法选择器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWasChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
#pragma mark - 创建 评论 的 输入框
- (void)createReply{
    self.viewOfBackground = [[BaseView alloc] initWithFrame:CGRectMake(0, -200, SCREEN_WIDTH, 200)];
    // 放弃回复 button
    UIButton *buttonOfResignReply = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 40, 40)];
    [buttonOfResignReply setTitle:@"✖️" forState:UIControlStateNormal];
    [buttonOfResignReply addTarget:self action:@selector(giveUpReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:buttonOfResignReply];
    // label 评论给
    UILabel *labelOfComments = [[UILabel alloc] init];
    labelOfComments.text = @"评论";
    [self.viewOfBackground addSubview:labelOfComments];
    [labelOfComments mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.viewOfBackground).offset(0);
        make.width.mas_offset(60);
        make.height.mas_offset(20);
        make.top.equalTo(self.viewOfBackground).offset(20);
    }];
    // 回复 button
    self.buttonOfReply = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 10, 40, 40)];
    [self.buttonOfReply setTitle:@"✔️" forState:UIControlStateNormal];
    [self.buttonOfReply addTarget:self action:@selector(sureReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:_buttonOfReply];
    // 输入的视图
    self.textView = [[UITextView alloc] init];
    [self.viewOfBackground addSubview:_textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.viewOfBackground).offset(15);
        make.right.equalTo(self.viewOfBackground).offset(-15);
        make.bottom.equalTo(self.viewOfBackground).offset(-15);
        make.height.mas_offset(120);
    }];
    self.viewOfBackground.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    [self.view addSubview:_viewOfBackground];
}
#pragma mark - 给键盘隐藏添加方法选择器
- (void) keyboardWasHidden:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    _viewOfBackground.frame = CGRectMake(0, -200, SCREEN_WIDTH, 200);
}
#pragma mark - 给肩膀改变添加方法选择器
- (void)KeyboardWasChange:(NSNotification *)notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    // 我也不知道为什么, 200 - 64 的这个地方应该是 200
    _viewOfBackground.frame = CGRectMake(0, SCREEN_HEIGHT - _keyboardSize.height - 200 - 64, SCREEN_WIDTH, 200);
}
#pragma mark - 放弃回复按钮的方法实现
- (void)giveUpReply:(UIButton *)button{
    [_textView resignFirstResponder];
}
#pragma mark - 回复的功能实现
- (void)reply:(UIButton *)button{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *user_id = [user objectForKey:@"user_id"];
    if (user_id){
        // textView 变成第一响应者
        [_textView becomeFirstResponder];
    } else {
        // 跳转到登录界面
        VCOfLogining *vcOfLogining = [[VCOfLogining alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vcOfLogining];
        [self presentViewController:navi animated:YES completion:^{
            
        }];
    }
}
#pragma mark - 确认回复
- (void)sureReply:(UIButton *)button{
    NSLog(@"%@", _textView.text);
    NSLog(@"button_tag%ld", _buttonOfReply.tag);

    //{"token":"0d4eeb8732f9ae2c73401002570ceb93","content":"有哲理","answer_id":"5292865"}
    // http://yiapi.xinli001.com/v2/yi/post-answer-reply.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0
    [ZWYNetTool POST:@"http://yiapi.xinli001.com/v2/yi/post-answer-reply.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:@"\"token\":\"0d4eeb8732f9ae2c73401002570ceb93\",\"content\":\"做人积极向上些\",\"answer_id\":\"5292865\"}" andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/json"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSLog(@"回复的反馈信息:%@", result);
        [_textView resignFirstResponder];
        [self handleData];
        [self.tableViewOfQAADetailedInformation reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"怎么东西")
    }];
    [self pleaseWait];
}
#pragma mark - 还未开放此功能
- (void)pleaseWait{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"这个功能目前还没有开放" message:@"你可以尝试别的东西" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 其他, 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
